package com.sgb.merchant.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;

import android.view.View;

import androidx.core.content.FileProvider;
import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;


import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import com.sgb.link.entity.EventConstant;

import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.DemandDetailEntity;

import com.sgb.link.router.PathMerchant;

import com.sgb.merchant.R;

import com.sgb.merchant.databinding.MerchantActivitySelfDemandDetailBinding;

import com.sgb.merchant.viewmodel.DemandDetailViewModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.download.DownloadListner;
import com.swgk.core.download.DownloadManager;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.FileUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.NumberUtil;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;


import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author: 王彬臣
 * @date: 2021/9/17
 * @Description: 我的投资需求详情
 */
@Route(path = PathMerchant.SelfDemandDetailActivity)
public class SelfDemandDetailActivity extends BaseActivity<DemandDetailViewModel, MerchantActivitySelfDemandDetailBinding> {
    @Autowired(name = RouterKey.NO, desc = "详情no")
    String no="";
    DemandDetailEntity mEntity;
    private static final String FILE_TYPE_RAR = ".rar";
    private static final String FILE_TYPE_ZIP = ".zip";
    private static final String FILE_TYPE_DOC = ".doc";
    private static final String FILE_TYPE_DOCX = ".docx";
    private static final String FILE_TYPE_PPT = ".ppt";
    private static final String FILE_TYPE_PPTX = ".pptx";
    private static final String FILE_TYPE_XLS = ".xls";
    private static final String FILE_TYPE_XLSX = ".xlsx";
    private static final String FILE_TYPE_PDF = ".pdf";
    private static final String FILE_TYPE_JPG = ".jpg";
    private static final String FILE_TYPE_PNG = ".png";
    private static final String FILE_TYPE_JPEG = ".jpeg";

    boolean isFristGetData = true;
    private DownloadManager mDownloadManager;
    private int id,position;

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_self_demand_detail;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(DemandDetailViewModel.class);

    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.includeTitle.titleView.setText("投资需求详情");
        mBinding.includeTitle.ivBack.setOnClickListener(v -> finish());
        mBinding.setClick(this);
        mViewModel.ldInfo.observe(this, this::setInfo);
        DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(true);

        mViewModel.getInfo(no);
        mViewModel.ldState.observe(this, state -> {
            switch (state) {//0未上架 1已删除 2正常
                case 1:
                    mBinding.sv.setVisibility(View.GONE);
                    mBinding.bidLayout.setVisibility(View.GONE);
                    mBinding.rlError.setVisibility(View.VISIBLE);
                    mBinding.noDataTv.setText(Html.fromHtml("当前数据已删除，请<u><font color='#5892FD'>返回列表</font></u>继续浏览吧~"));
                    mBinding.noDataTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    break;
                case 2:
                    mBinding.sv.setVisibility(View.VISIBLE);
                    mBinding.bidLayout.setVisibility(View.VISIBLE);
                    mBinding.rlError.setVisibility(View.GONE);
                    clickEvent();
                    break;
            }
        });
        mViewModel.ldItemState.observe(this,state->{
            switch (state){//0未上架 1已删除 2正常
                case 0:
                    MToast.showToast(this,"当前数据已下架");

                    break;
                case 1:
                    MToast.showToast(this,"当前数据已删除");

                    break;

            }
        });
        mViewModel.ldDel.observe(this,result->{
            //刷新列表页
            EventBus.getDefault()
                    .post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_REFRESH_DEMANDS));
            finish();
        });
        mViewModel.ldStatus.observe(this,result->{
            //刷新列表页
            EventBus.getDefault()
                    .post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_REFRESH_DEMANDS));
            if (mEntity.getDemandStatus().equals("0")) {
                mEntity.setDemandStatus("1");
            } else {
                mEntity.setDemandStatus("0");
            }
            setInfo(mEntity);
        });
    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Override
    public void onClick(View v) {
        id = v.getId();
        if (id == R.id.tv_more) {
            ARouter.getInstance().build(PathMerchant.DemandListActivity).navigation();
        }else if (id == R.id.tv_down) {//下载
            Uri uri = Uri.parse(mEntity.getFileUrl());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }else {
 /*           DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(true);
            mViewModel.getState(no);*/
            clickEvent();
        }
    }

    private void clickEvent() {

        if (id == R.id.tv_put_away) {
            new RoundDialog.Builder(this)
                    .title("温馨提示")
                    .content("确定上架该条信息？")
                    .cancel("取消")
                    .confirm("确定")
                    .cancelable(false)
                    .confirmCallback(v12 -> {
                        DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(true);
                        mViewModel.updateDemands(no,"1");
                    }).show();
        }else if(id==R.id.tv_down_away){
            new RoundDialog.Builder(this)
                    .title("温馨提示")
                    .content("下架该信息后，前台将不再继续展示，确定下架？")
                    .cancel("取消")
                    .confirm("确定")
                    .cancelable(false)
                    .confirmCallback(v12 -> {
                        DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(true);
                        mViewModel.updateDemands(no,"0");
                    }).show();
        } else if (id == R.id.tv_del) {
            new RoundDialog.Builder(this)
                    .title("温馨提示")
                    .content("请问是否确认删除？")
                    .cancel("取消")
                    .confirm("确定")
                    .cancelable(false)
                    .confirmCallback(v12 -> {
                        DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(true);
                        mViewModel.delProject(no);
                    }).show();
        } else if (id == R.id.tv_edit) {
            ActivityJump.startActivity(PathMerchant.PublishDemandActivity, Pair.create(RouterKey.NO,no));
        }
    }

    private void startDownloads(String uri, File file, String fileName) {
        //创建下载任务管理器
        mDownloadManager = DownloadManager.getInstance();
        //将下载任务添加至任务管理器中，并创建下载线程
        mDownloadManager.add(uri, file.getAbsolutePath(), fileName, new DownloadListner() {
            private int load = 0;

            @Override
            public void onFinished() { //下载完成
                Uri uri = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileProvider.getUriForFile(SelfDemandDetailActivity.this, getPackageName() + ".fileProvider", new File(getExternalFilesDir("file" + File.separator + "download"), fileName));
                } else {
                    uri = Uri.fromFile(file);
                }

                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                startActivity(intent);
            }

            @Override
            public void onProgress(float progress, boolean isDownloading) { //更新中

            }

            @Override
            public void onPause() { //暂停

            }

            @Override
            public void onCancel() { //取消

            }
        });
        mDownloadManager.download(uri); //继续下载
    }

    @SuppressLint("AutoDispose")
    public void setInfo(DemandDetailEntity entity) {
        mEntity = entity;
        mBinding.bidLayout.setVisibility(View.VISIBLE);
        mBinding.sv.setVisibility(View.VISIBLE);
        mBinding.tvTitle.setText(entity.getDemandName());
        mBinding.tvType.setText(entity.getDemandTypeName());
        mBinding.tvPrice.setText(NumberUtil.price(Double.valueOf(entity.getDemandMoney())) + "元");
        mBinding.tvArea.setText(entity.getCityStr());
        mBinding.tvPerson.setText(entity.getLinkName());
        mBinding.tvPhone.setText(entity.getLinkPhone());
        mBinding.tvTime.setText(DateUtils.stampToDay6(entity.getCreateTime()));
        mBinding.tvInfo.setText(entity.getDemandInfo());

        if (!TextUtils.isEmpty(entity.getFileUrl())) {
            mBinding.llFile.setVisibility(View.VISIBLE);
            String fileName = entity.getFileName();
            mBinding.tvName.setText(fileName);
            if (fileName.endsWith(FILE_TYPE_RAR) || fileName.endsWith(FILE_TYPE_ZIP)) {
                mBinding.image.setImageResource(R.mipmap.merchant_icon_zip);
            } else if (fileName.endsWith(FILE_TYPE_DOC) || fileName.endsWith(FILE_TYPE_DOCX)) {
                mBinding.image.setImageResource(R.mipmap.merchant_icon_doc);
            } else if (fileName.endsWith(FILE_TYPE_PPT) || fileName.endsWith(FILE_TYPE_PPTX)) {
                mBinding.image.setImageResource(R.mipmap.merchant_icon_ppt);
            } else if (fileName.endsWith(FILE_TYPE_XLS) || fileName.endsWith(FILE_TYPE_XLSX)) {
                mBinding.image.setImageResource(R.mipmap.merchant_icon_xlsx);
            } else if (fileName.endsWith(FILE_TYPE_PDF)) {
                mBinding.image.setImageResource(R.mipmap.merchant_icon_pdf);
            } else if (fileName.endsWith(FILE_TYPE_JPG) || fileName.endsWith(FILE_TYPE_JPEG) || fileName.endsWith(FILE_TYPE_PNG)) {
                mBinding.image.setImageResource(R.mipmap.merchant_icon_img_type);
            }
            Observable.just(entity.getFileUrl()).
                    map(s -> FileUtil.getFileSize(s)).//子线程里获取文件大小
                    subscribeOn(Schedulers.io()).
                    observeOn(AndroidSchedulers.mainThread()).
                    subscribe(s -> mBinding.tvSize.setText(s));

        }
        if (isFristGetData) {
            isFristGetData = false;
            mViewModel.getRecommendsList(no, entity.getDemandTypeNo() + "");
        }
        switch (entity.getDemandStatus()){//0 下架 1上架
            case "0":
                mBinding.tvStatus.setText("下架");
                mBinding.tvPutAway.setVisibility(View.VISIBLE);
                mBinding.tvEdit.setVisibility(View.VISIBLE);
                mBinding.tvDel.setVisibility(View.VISIBLE);
                mBinding.tvDownAway.setVisibility(View.GONE);
                break;
            case "1":
                mBinding.tvStatus.setText("上架");
                mBinding.tvPutAway.setVisibility(View.GONE);
                mBinding.tvEdit.setVisibility(View.GONE);
                mBinding.tvDel.setVisibility(View.GONE);
                mBinding.tvDownAway.setVisibility(View.VISIBLE);
                break;
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MainEvent event) {
        if (event == null) return;
        if (event.getMessageTag() == EventConstant.EVEN_MERCHANT_SELF_REFRESH_DEMANDS_DETAIL) {
            DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
            if(!TextUtils.isEmpty(no))
            mViewModel.getInfo(no);
        }
        EventBus.getDefault().removeStickyEvent(event);
    }
}
